package com.runa.monitor.platinterface.mqtt.vo;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

@Slf4j
public class FourGVO extends FieldHandler {

    @SneakyThrows
    protected static <T> T generate(Class<T> clazz, String json) {
        T t = clazz.newInstance();
        try {
            char[] chars = json.toCharArray();
            Integer begin = 0;
            boolean f = false;
            for (Integer i = 0; i < chars.length; i++) {
                if (!f & chars[i] == ',') {
                    begin = i + 1;
                    continue;
                }

                if (chars[i] == '[') {
                    f = true;
                    continue;
                }

                if (f) {
                    if (chars[i] == ']') {
                        String substring = json.substring(begin, i+1);
                        String[] split = substring.split(":");
                        if (null != split && split.length == 2) {
                            try {
                                Field item = clazz.getDeclaredField(split[0]);
                                item.setAccessible(true);
                                if (split.length > 1)
                                    item.set(t, split[1]);
                            } catch (NoSuchFieldException e) {
                                log.error("对应文档无此字段，无法解析" + split[0]);
                            }
                        }
                        f = false;
                    }
                    continue;
                } else if ((i + 1 == chars.length) || chars[i+1] == ',') {
                    String substring = json.substring(begin, i+1);
                    String[] split = substring.split(":");
                    if (null != split && split.length == 2) {
                        try {
                            Field item = clazz.getDeclaredField(split[0]);
                            item.setAccessible(true);
                            if (split.length > 1)
                                item.set(t, split[1]);
                        } catch (NoSuchFieldException e) {
                            log.error("对应文档无此字段，无法解析" + split[0]);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("", e);
        }
        return t;

    }


}
